package net.sinmetal.twitcockpit.controller;

import java.util.ArrayList;
import java.util.List;

import net.sinmetal.twitcockpit.model.AutoPost;
import net.sinmetal.twitcockpit.model.config.AuthUser;
import net.sinmetal.twitcockpit.modelvar.AutoPostVar;
import net.sinmetal.twitcockpit.service.AutoPostService;
import net.sinmetal.twitcockpit.service.ConfigService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * IndexController
 *
 * @author Sinmetal
 *
 */
public class IndexController extends Controller {

    private ConfigService configService = new ConfigService();

    private AutoPostService autoPostService = new AutoPostService();

    /**
     * トップページ表示
     */
    @Override
    public Navigation run() throws Exception {
        UserService userService = UserServiceFactory.getUserService();
        if (!userService.isUserLoggedIn()) {
            response.sendRedirect(userService.createLoginURL("/"));
            return null;
        }
        User user = userService.getCurrentUser();
        AuthUser authUser = configService.getAuthUser();
        if (authUser == null || !authUser.constains(user)) {
            return redirect("/error/notFound.html");
        }

        List<AutoPostVar> autoPostVars = new ArrayList<AutoPostVar>();
        List<AutoPost> autoPosts = autoPostService.queryAll();
        for (AutoPost autoPost : autoPosts) {
            autoPostVars.addAll(autoPost.getAutoPostVars());
        }
        requestScope("autoPostVars", autoPostVars);
        return forward("index.jsp");
    }
}